package silent.jdbc;

import java.sql.*;

/**
 * @author liutao
 * Date 2021/7/17 10:47 上午
 * Description:
 * Version: 1.0
 **/
public class jdbc {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // 加载MySQL的JDBC的驱动
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://127.0.0.1:3306/test";
        String username = "root";
        String password = "123456";

        // 创建与MySQL数据库的连接类的实例
        Connection conn = DriverManager.getConnection(url, username, password);

        //插入:
        try {
            // 禁用自动提交
            conn.setAutoCommit(false);

            // 用conn创建Statement对象类实例
            Statement sql_statement = conn.createStatement();


            // 插入数据
            sql_statement.executeUpdate("insert person values(10,'aabb', 88)");
            conn.commit();
        }catch ( Exception e){
            e.printStackTrace();
            if (conn != null){
                //事务回滚
                conn.rollback();
            }
        }
    //查询:
        try {
            // 用conn创建Statement对象类实例
            Statement sql_statement = conn.createStatement();

            // 执行查询，用ResultSet类的对象，返回查询的结果
            String query = "select * from person";
            ResultSet result = sql_statement.executeQuery(query);

            // 处理结果
            while (result.next()) {
                int id = result.getInt("id");
                String name = result.getString("name");
                String age = result.getString("age");

                System.out.println("id: " + id + " name: " + name + " age: " + age);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    //修改:
       //SQL语句已发送给数据库，并编译好为执行作好准备
        PreparedStatement pstmt = conn.prepareStatement(
                        "UPDATE  person   SET age= ? WHERE id = ?");
         //对占位符进行初始化
         pstmt.setString(1,"silent");
         pstmt.setInt(2,1);
         //执行SQL语句
        pstmt.executeUpdate();





    }
}
